package com.example.seata.order.service.impl;

import com.example.seata.order.entity.AccountTbl;
import com.example.seata.order.entity.OrderTbl;
import com.example.seata.order.entity.StorageTbl;
import com.example.seata.order.feign.AccountFeignClient;
import com.example.seata.order.feign.StockFeignClient;
import com.example.seata.order.mapper.OrderTblMapper;
import com.example.seata.order.service.IOrderTblService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianshuo
 * @since 2021-05-15
 */
@Slf4j
@Service
public class OrderTblServiceImpl extends ServiceImpl<OrderTblMapper, OrderTbl> implements IOrderTblService {

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private StockFeignClient stockFeignClient;

    /**
     * 创建订单
     *
     * @param orderTbl
     * @return
     *
     */
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean create(OrderTbl orderTbl) {

            StorageTbl storageTbl = new StorageTbl();
            storageTbl.setCount(orderTbl.getCount());
            storageTbl.setCommodityCode(orderTbl.getCommodityCode());
            // 减库存
            String deduct = stockFeignClient.deduct(storageTbl);
            if (!deduct.equals("ok")) {
                throw new RuntimeException("库存扣减失败");
            }

            AccountTbl accountTbl = new AccountTbl();
            accountTbl.setMoney(orderTbl.getCount() * orderTbl.getMoney());
            accountTbl.setUserId(orderTbl.getUserId());
            // 记账
            String debit = accountFeignClient.debit(accountTbl);
            if (!debit.equals("ok")) {
                throw new RuntimeException("记账失败");
            }


            //生成订单
            save(orderTbl);
            return true;
    }
}
